<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          v-hasPermi="['11410']"
          @click="handleAdd"
          >添加角色</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tableList" :border="true">
      <el-table-column
        label="角色名称"
        prop="roleName"
        align="center"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="人数" prop="userNum" align="center" />
      <el-table-column label="位置排序" prop="sort" align="center" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
        width="100"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            v-hasPermi="['11420']"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            v-hasPermi="['11430']"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        :validate-on-rule-change="false"
        label-width="80px"
      >
        <!-- *角色名称，*分配权限（复选列表）、顺序码 -->
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="分配权限" prop="menuIds">
          <el-checkbox
            v-model="menuExpand"
            @change="handleCheckedTreeExpand($event, 'menu')"
            >展开/折叠</el-checkbox
          >
          <el-checkbox
            v-model="menuNodeAll"
            @change="handleCheckedTreeNodeAll($event, 'menu')"
            >全选/全不选</el-checkbox
          >
          <el-checkbox
            v-model="menuCheckStrictly"
            @change="handleCheckedTreeConnect($event, 'menu')"
            >父子联动</el-checkbox
          >
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            ref="menu"
            node-key="thecode"
            :check-strictly="!menuCheckStrictly"
            empty-text="加载中，请稍后"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
        <el-form-item label="位置排序" prop="sort">
          <el-input-number
            v-model="form.sort"
            controls-position="right"
            :min="0"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listData,
  getData,
  delData,
  addData,
  updateData,
} from "@/api/system/adminRole";
import { getJurisdictionInfo } from "@/api/common";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "adminRole",
  data() {
    return {
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      showSearch: true,
      loading: true,
      tableList: [],
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      title: "",
      open: false,
      form: {},
      rules: {
        roleName: [
          { required: true, message: "角色名称不能为空", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        menuIds: [{ required: true, message: "请分配权限", trigger: "blur" }],
      },
      /** 分配权限 */
      menuCheckStrictly: true,
      menuExpand: false,
      menuNodeAll: false,
      // 菜单列表
      menuOptions: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
    };
  },
  components: {
    Treeselect,
  },
  created() {
    this.getList();
    this.getMenuTreeselect();
  },
  mounted() {},
  methods: {
    /* deptIdChange(val) {
      this.$nextTick(() => {
        this.$refs.form.validateField('deptId');
      })
    }, */
    /** 查询管理员列表 */
    getList() {
      this.loading = true;
      listData(this.queryParams).then((response) => {
        this.tableList = response.result.rows;
        this.total = response.result.total;
        this.loading = false;
      });
    },
    /** 查询菜单树结构 */
    getMenuTreeselect() {
      getJurisdictionInfo().then((response) => {
        this.menuOptions = response.result;
        console.log("menuOptions---", this.menuOptions);
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const roleId = row.theid || this.ids;
      getData(roleId).then((response) => {
        console.log("response---", response);
        this.form = response.result;
        this.open = true;
        if (response.result.menuIds != null) {
          this.$nextTick(() => {
            let checkedKeys = response.result.menuIds.split(",").map((ele) => {
              return Number(ele);
            });
            console.log("checkedKeys---", checkedKeys);
            checkedKeys.forEach((v) => {
              this.$nextTick(() => {
                this.$refs.menu.setChecked(v, true, false);
              });
            });
          });
        }
        this.title = "修改";
      });
    },
    /** 提交按钮 */
    submitForm() {
      // menuIds 必填
      let checkedNodes = this.getMenuAllCheckedNodes();
      this.form.jurisdiction = checkedNodes[0].join(",");
      this.form.menuIds = checkedNodes[1].join(",");
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.theid != undefined) {
            updateData(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addData(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roleIds = row.theid || this.ids;
      this.$confirm("是否确认删除?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          // 调接口
          return delData(roleIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 导出按钮操作 */
    handleExport() {
      // const queryParams = this.queryParams;
      this.$confirm("是否确认导出?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          // 调接口导出表
          // return exportRole(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      this.menuExpand = false;
      this.menuNodeAll = false;
      this.menuCheckStrictly = true;
      this.form = {
        roleName: undefined,
        jurisdiction: undefined,
        menuIds: undefined,
        sort: 0,
      };
      this.resetForm("form");
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      let treeList = this.menuOptions;
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      this.$refs.menu.setCheckedNodes(value ? this.menuOptions : []);
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      this.menuCheckStrictly = value ? true : false;
    },
    // 所有菜单节点数据 Keys
    /* getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    }, */
    // 所有菜单节点数据 Nodes
    getMenuAllCheckedNodes() {
      // 目前被选中的菜单节点
      let checkedNodes = this.$refs.menu.getCheckedNodes();
      // 半选中的菜单节点
      let halfCheckedNodes = this.$refs.menu.getHalfCheckedNodes();
      checkedNodes.unshift.apply(checkedNodes, halfCheckedNodes);
      let jurArr = [],
        menuIdarr = [];
      checkedNodes.forEach((item, index) => {
        jurArr.push(item.label);
        menuIdarr.push(item.thecode);
      });
      return [jurArr, menuIdarr];
    },
  },
};
</script>

<style scoped lang="scss">
// /deep/
</style>
